#include "bluetooth_manager.h"
#include <WiFi.h>

// 静态实例指针
BluetoothManager* BluetoothManager::instance = nullptr;

// ==================== 构造函数和析构函数 ====================

BluetoothManager::BluetoothManager() {
    btSerial = nullptr;
    currentState = BT_DISABLED;
    deviceName = "sandart";
    isEnabled = false;
    autoDisableAfterWiFi = true;
    lastHeartbeat = 0;
    connectedDeviceName = "";
    commandHandler = nullptr;
    wifiConfigHandler = nullptr;
    
    // 设置静态实例指针
    instance = this;
}

BluetoothManager::~BluetoothManager() {
    disable();
    if (btSerial) {
        delete btSerial;
        btSerial = nullptr;
    }
    instance = nullptr;
}

// ==================== 初始化和控制 ====================

bool BluetoothManager::initialize(const String& name) {
    Serial.println("🔵 初始化蓝牙管理器...");
    
    if (btSerial) {
        Serial.println("⚠️ 蓝牙已初始化，跳过重复初始化");
        return true;
    }
    
    deviceName = name;
    currentState = BT_INITIALIZING;
    
    // 创建蓝牙串口实例
    btSerial = new BluetoothSerial();
    if (!btSerial) {
        Serial.println("❌ 蓝牙串口创建失败");
        currentState = BT_ERROR;
        return false;
    }
    
    Serial.printf("✅ 蓝牙管理器初始化完成，设备名称: %s\n", deviceName.c_str());
    currentState = BT_READY;
    return true;
}

void BluetoothManager::enable() {
    if (!btSerial) {
        Serial.println("❌ 蓝牙未初始化，无法启用");
        return;
    }
    
    if (isEnabled) {
        Serial.println("⚠️ 蓝牙已启用");
        return;
    }
    
    Serial.printf("🔵 启用蓝牙配对模式，设备名称: %s\n", deviceName.c_str());
    
    // 启动蓝牙服务
    if (!btSerial->begin(deviceName)) {
        Serial.println("❌ 蓝牙启动失败");
        currentState = BT_ERROR;
        return;
    }
    
    isEnabled = true;
    currentState = BT_READY;
    lastHeartbeat = millis();
    
    Serial.println("✅ 蓝牙配对模式已启用");
    Serial.println("📱 请在手机上搜索并连接蓝牙设备: " + deviceName);
    Serial.println("💡 支持的命令格式:");
    Serial.println("   - 设备控制: start, stop, home, sweep 等");
    Serial.println("   - WiFi配置: {\"wifi\":{\"ssid\":\"网络名\",\"password\":\"密码\"}}");
    Serial.println("   - 状态查询: status");
}

void BluetoothManager::disable() {
    if (!isEnabled) {
        return;
    }
    
    Serial.println("🔵 关闭蓝牙配对模式");
    
    if (btSerial) {
        btSerial->end();
    }
    
    isEnabled = false;
    currentState = BT_DISABLED;
    connectedDeviceName = "";
    
    Serial.println("✅ 蓝牙已关闭");
}

bool BluetoothManager::isBluetoothEnabled() const {
    return isEnabled;
}

BluetoothState BluetoothManager::getState() const {
    return currentState;
}

// ==================== 连接管理 ====================

bool BluetoothManager::isConnected() const {
    if (!btSerial || !isEnabled) {
        return false;
    }
    return btSerial->hasClient();
}

String BluetoothManager::getConnectedDevice() const {
    return connectedDeviceName;
}

void BluetoothManager::disconnect() {
    if (btSerial && isConnected()) {
        btSerial->disconnect();
        connectedDeviceName = "";
        Serial.println("🔵 蓝牙客户端已断开");
    }
}

// ==================== 配置方法 ====================

void BluetoothManager::setDeviceName(const String& name) {
    deviceName = name;
    Serial.printf("🔵 蓝牙设备名称设置为: %s\n", name.c_str());
}

void BluetoothManager::setAutoDisableAfterWiFi(bool enable) {
    autoDisableAfterWiFi = enable;
    Serial.printf("🔵 WiFi连接后自动关闭蓝牙: %s\n", enable ? "启用" : "禁用");
}

void BluetoothManager::setCommandHandler(std::function<String(const String&)> handler) {
    commandHandler = handler;
    Serial.println("✅ 蓝牙命令处理器已设置");
}

void BluetoothManager::setWiFiConfigHandler(std::function<void(const String&, const String&)> handler) {
    wifiConfigHandler = handler;
    Serial.println("✅ WiFi配置处理器已设置");
}

// ==================== 运行时更新 ====================

void BluetoothManager::update() {
    if (!btSerial || !isEnabled) {
        return;
    }
    
    // 检查连接状态变化
    bool connected = isConnected();
    static bool lastConnected = false;
    
    if (connected && !lastConnected) {
        currentState = BT_CONNECTED;
        Serial.println("🔵 蓝牙客户端已连接");
        sendJSON("connect", true, "蓝牙连接成功");
    } else if (!connected && lastConnected) {
        currentState = BT_READY;
        connectedDeviceName = "";
        Serial.println("🔵 蓝牙客户端已断开");
    }
    lastConnected = connected;
    
    // 处理接收到的数据
    if (connected) {
        processIncomingData();
        
        // 发送心跳包（每30秒）
        if (millis() - lastHeartbeat > 30000) {
            sendHeartbeat();
            lastHeartbeat = millis();
        }
    }
    
    // 检查WiFi状态，自动关闭蓝牙
    if (autoDisableAfterWiFi && WiFi.isConnected() && isEnabled) {
        Serial.println("🔵 WiFi已连接，自动关闭蓝牙配对模式");
        disable();
    }
}

// ==================== 数据处理 ====================

void BluetoothManager::processIncomingData() {
    if (!btSerial || !btSerial->available()) {
        return;
    }
    
    String receivedData = btSerial->readString();
    receivedData.trim();
    
    if (receivedData.length() == 0) {
        return;
    }
    
    Serial.printf("🔵 收到蓝牙数据: %s\n", receivedData.c_str());
    
    // 尝试解析WiFi配置
    String ssid, password;
    if (parseWiFiConfig(receivedData, ssid, password)) {
        handleWiFiConfig(ssid, password);
        return;
    }
    
    // 处理普通命令
    String command = parseCommand(receivedData);
    if (command.length() > 0) {
        handleBluetoothCommand(command);
    }
}

void BluetoothManager::handleBluetoothCommand(const String& command) {
    Serial.printf("🔵 处理蓝牙命令: %s\n", command.c_str());
    
    // 使用命令处理器处理命令
    if (commandHandler) {
        String response = commandHandler(command);
        sendResponse(response);
    } else {
        sendJSON(command, false, "命令处理器未设置");
    }
}

void BluetoothManager::handleWiFiConfig(const String& ssid, const String& password) {
    Serial.printf("🔵 收到WiFi配置: SSID=%s\n", ssid.c_str());
    
    if (wifiConfigHandler) {
        sendJSON("wifi", true, "开始配置WiFi连接");
        wifiConfigHandler(ssid, password);
    } else {
        sendJSON("wifi", false, "WiFi配置处理器未设置");
    }
}

// ==================== 数据发送 ====================

void BluetoothManager::sendResponse(const String& response) {
    if (!btSerial || !isConnected()) {
        return;
    }
    
    btSerial->println(response);
    Serial.printf("🔵 发送蓝牙响应: %s\n", response.c_str());
}

void BluetoothManager::sendMessage(const String& message) {
    sendResponse(message);
}

void BluetoothManager::sendStatus(const String& status) {
    sendJSON("status", true, status);
}

void BluetoothManager::sendHeartbeat() {
    sendJSON("heartbeat", true, "连接正常");
}

void BluetoothManager::sendJSON(const String& command, bool success, const String& message, const String& data) {
    if (!btSerial || !isConnected()) {
        return;
    }
    
    DynamicJsonDocument doc(512);
    doc["command"] = command;
    doc["success"] = success;
    doc["timestamp"] = millis();
    
    if (message.length() > 0) {
        doc["message"] = message;
    }
    
    if (data.length() > 0) {
        doc["data"] = data;
    }
    
    String jsonResponse;
    serializeJson(doc, jsonResponse);
    
    btSerial->println(jsonResponse);
    Serial.printf("🔵 发送JSON响应: %s\n", jsonResponse.c_str());
}

// ==================== 数据解析 ====================

String BluetoothManager::parseCommand(const String& input) {
    // 去除首尾空格
    String command = input;
    command.trim();
    
    // 如果是JSON格式，尝试解析command字段
    if (command.startsWith("{") && command.endsWith("}")) {
        DynamicJsonDocument doc(512);
        DeserializationError error = deserializeJson(doc, command);
        
        if (error == DeserializationError::Ok && doc.containsKey("command")) {
            return doc["command"].as<String>();
        }
    }
    
    // 返回原始命令
    return command;
}

bool BluetoothManager::parseWiFiConfig(const String& input, String& ssid, String& password) {
    if (!input.startsWith("{") || !input.endsWith("}")) {
        return false;
    }
    
    DynamicJsonDocument doc(512);
    DeserializationError error = deserializeJson(doc, input);
    
    if (error != DeserializationError::Ok) {
        return false;
    }
    
    // 检查是否包含wifi配置
    if (!doc.containsKey("wifi")) {
        return false;
    }
    
    JsonObject wifi = doc["wifi"];
    if (!wifi.containsKey("ssid") || !wifi.containsKey("password")) {
        return false;
    }
    
    ssid = wifi["ssid"].as<String>();
    password = wifi["password"].as<String>();
    
    return true;
}

// ==================== 状态查询 ====================

void BluetoothManager::printStatus() {
    Serial.println("=== 蓝牙管理器状态 ===");
    Serial.printf("设备名称: %s\n", deviceName.c_str());
    Serial.printf("启用状态: %s\n", isEnabled ? "✅启用" : "❌禁用");
    
    String stateNames[] = {"禁用", "初始化中", "就绪", "已连接", "错误"};
    if (currentState < 5) {
        Serial.printf("当前状态: %s\n", stateNames[currentState].c_str());
    }
    
    Serial.printf("连接状态: %s\n", isConnected() ? "✅已连接" : "❌未连接");
    if (connectedDeviceName.length() > 0) {
        Serial.printf("连接设备: %s\n", connectedDeviceName.c_str());
    }
    
    Serial.printf("WiFi后自动关闭: %s\n", autoDisableAfterWiFi ? "✅启用" : "❌禁用");
    Serial.printf("命令处理器: %s\n", commandHandler ? "✅已设置" : "❌未设置");
    Serial.printf("WiFi配置处理器: %s\n", wifiConfigHandler ? "✅已设置" : "❌未设置");
    Serial.println("=====================");
}

String BluetoothManager::getStatusJSON() {
    DynamicJsonDocument doc(512);
    
    doc["deviceName"] = deviceName;
    doc["enabled"] = isEnabled;
    doc["state"] = (int)currentState;
    doc["connected"] = isConnected();
    doc["autoDisableAfterWiFi"] = autoDisableAfterWiFi;
    
    if (connectedDeviceName.length() > 0) {
        doc["connectedDevice"] = connectedDeviceName;
    }
    
    String result;
    serializeJson(doc, result);
    return result;
}

// ==================== 静态回调处理 ====================

void BluetoothManager::onBluetoothCallback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) {
    if (instance) {
        instance->handleCallback(event, param);
    }
}

void BluetoothManager::handleCallback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) {
    switch (event) {
        case ESP_SPP_INIT_EVT:
            Serial.println("🔵 蓝牙SPP初始化完成");
            break;
            
        case ESP_SPP_SRV_OPEN_EVT:
            Serial.println("🔵 蓝牙服务器开启");
            break;
            
        case ESP_SPP_OPEN_EVT:
            Serial.println("🔵 蓝牙连接建立");
            currentState = BT_CONNECTED;
            break;
            
        case ESP_SPP_CLOSE_EVT:
            Serial.println("🔵 蓝牙连接关闭");
            currentState = BT_READY;
            connectedDeviceName = "";
            break;
            
        case ESP_SPP_DATA_IND_EVT:
            // 数据接收在update()中处理
            break;
            
        default:
            break;
    }
}
